/*
 * acooly.cn Inc.
 * Copyright (c) 2016 All Rights Reserved.
 * create by zhangpu 
 * date:2016年4月29日
 *
 */
package com.acooly.module.openapi.client.api.util;

import com.acooly.core.utils.GenericsUtils;
import com.acooly.core.utils.Reflections;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.anotation.ApiMsg;
import com.acooly.module.openapi.client.api.message.ApiMessage;
import com.google.common.reflect.TypeToken;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;

/**
 * @author zhangpu
 */
public class ApiClientUtils {

    /**
     * 获取报文对应的服务名
     *
     * @param apiMessage
     * @return
     */
    public static String getServiceName(ApiMessage apiMessage) {
        String serviceName = apiMessage.getService();
        if (Strings.isBlank(serviceName)) {
            ApiMsg apiMsg = apiMessage.getClass().getAnnotation(ApiMsg.class);
            if (apiMsg != null) {
                serviceName = apiMsg.service();
            }
        }
        return serviceName;
    }

    /**
     * 获取集合对象的泛型参数类型
     *
     * @param clazz
     * @param field
     * @return
     */
    public static Class<?> getFieldGenericType(Field field) {
        TypeToken<?> t = TypeToken.of(field.getGenericType());
        if (t.getType() instanceof ParameterizedType) {
            Type type = ((ParameterizedType) t.getType()).getActualTypeArguments()[0];
            if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
                return ((Class<?>) ((ParameterizedType) type).getRawType());
            } else if (type instanceof Class) {
                return (Class<?>) type;
            } else {
                // 获取基础POJO的泛型
                Class<?> cc = field.getDeclaringClass();
                Class<?> tt = null;
                do {
                    tt = GenericsUtils.getSuperClassGenricType(cc);
                    if (tt != Object.class) {
                        break;
                    }
                    cc = cc.getSuperclass();
                } while (cc != Object.class);
                return tt;
            }
        }
        return null;
    }

    public static Class<?> getFieldGenericType(Class<?> clazz, String fieldName) {
        Set<Field> fields = Reflections.getFields(clazz);
        Field f = null;
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                f = field;
                break;
            }
        }
        if (f == null) {
            throw new RuntimeException("Class " + clazz + "没有属性：" + fieldName);
        }
        return getFieldGenericType(f);
    }

}
